package org.papervision3d.materials
{
	import flash.display.Sprite;
	import flash.display.DisplayObjectContainer;
	import flash.display.DisplayObject;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class PostItMaterial extends BitmapMaterial
	{
		
		public function get baseMaterial() : MovieMaterial {
			return _baseMaterial;
		}
		
		public function set rect( rect : Rectangle ) : void {
			postItsLayer.scrollRect = rect;
			postItsLayer.x = rect.x;
			postItsLayer.y = rect.y;
		}
		public function get rect() : Rectangle {
			return postItsLayer.scrollRect;
		}
		
		function PostItMaterial( baseMaterial : MovieMaterial, specificLayer : DisplayObjectContainer = null, transparent:Boolean=false, initObject:Object=null)
		{
			_baseMaterial = baseMaterial;
			init( specificLayer );
			super( baseMaterial.bitmap, baseMaterial );
		}
		
		
		public function addPostit( p : DisplayObject ) : void {
			postItsLayer.addChild( p );
			_aPostIt.push( p );
			updateBitmap();
		}
		public function removePostit( p : DisplayObject ) : void {
			postItsLayer.removeChild( p );
			var delId : int = _aPostIt.indexOf( p );
			if( delId > -1 )_aPostIt.splice( delId, 1 );
			updateBitmap();
		}
		
		public function getPostits() : Array {
			var a : Array = new Array();
			var len : int = postItsLayer.numChildren;
			while( --len > -1 ) a.push( postItsLayer.getChildAt( len ) );
			return a;
		}
		
		
		override public function updateBitmap():void {
			baseMovie.setChildIndex( postItsLayer, baseMovie.numChildren-1 );
			_baseMaterial.updateBitmap();
		}
		
		public function getObjectUnderPoint( p : Point ) : DisplayObject {
			var postit : DisplayObject;
			var b : Rectangle;
			for each( postit in _aPostIt ) {
				b = postit.getBounds( postItsLayer );
				if( b.containsPoint( p ) ) return postit;
			}
			trace( "PostItMaterial.getObjectUnderPoint -- null" );
			return null;
		} 
		
		
		//_________________________________________________________________________________
		//																			PRIVATES
		
		private function init( specificLayer : DisplayObjectContainer ) : void {
			_aPostIt = new Array();
			baseMovie = (specificLayer ) ? specificLayer : _baseMaterial.movie as DisplayObjectContainer;
			postItsLayer = new Sprite();
			baseMovie.addChild( postItsLayer );
		}
		
		private var _baseMaterial : MovieMaterial;
		private var baseMovie : DisplayObjectContainer;
		
		private var postItsLayer : Sprite;
		private var _aPostIt : Array;
		
	}
}